package com.manager.common.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("all")
public class ObjectUtils {

	public static  <T> List<T>  jsonArray2Bean(JSONArray jsonArray,Class<T> clazz){
		List<T> list = new ArrayList<>();

		for(int i = 0; i < jsonArray.size() ; i++) {
			T t;
			if(!ClassUtils.isSimpleType(clazz)){
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				t = (T) JSONObject.toBean(jsonObject, clazz);
			}else {
				t = (T)jsonArray.get(i);
			}
			list.add(t);
		}

		return list;
	}

	public static <T> List<T> jsonArray2Bean(String jsonArrayStr, Class<T> claz){
		JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);
		return jsonArray2Bean(jsonArray, claz);
	}

	public static void jsonArraySet(JSONArray jsonArray,JSONObject object,String field){
		for(int i = 0;i < jsonArray.size();i++){
			JSONObject temp = jsonArray.getJSONObject(i);
			if(temp.getString(field).equals(object.getString(field))){
				return;
			}
		}
		jsonArray.add(object);
	}

	private static <T> T json2Bean(JSONObject jsonObject, Set<Field> fieldList, Class<T> claz) throws  Exception{
		Iterator iterator =  jsonObject.keys();
		Object object = claz.newInstance();

		while (iterator.hasNext()){
			String key = String.valueOf(iterator.next());
			for(Field field:fieldList){
				if(field.getName().equals(key)){
					Object val = jsonObject.get(key);
					ClassUtils.setFieldValue(object, String.valueOf(val), field);
					break;
				}
			}
		}
		return (T)object;
	}

	public static <T> T json2Bean(String jsonStr, Class<T> claz) throws  Exception{
		Set<Field> fieldList = new HashSet<>();

		fieldList.addAll(Arrays.asList(claz.getDeclaredFields()));
		fieldList.addAll(Arrays.asList(claz.getFields()));

		return json2Bean(JSONObject.fromObject(jsonStr), fieldList,claz);

	}

	public static <T> T json2Bean(JSONObject json, Class<T> claz) throws  Exception{
		Set<Field> fieldList = new HashSet<>();
		Class<?> temp = claz;
		while (true) {
			try{
				if(temp == null || temp.isInterface() || temp.equals(Object.class)){
					break;
				}
				List<Field> tempFieldList = Arrays.asList(temp.getDeclaredFields());
				for (Field field : tempFieldList) {
					fieldList.add(field);
				}
			}catch (Exception e){
				e.printStackTrace();
			}
			temp = temp.getSuperclass();
		}

		return json2Bean(json, fieldList,claz);

	}

	public static JSONArray getJSONArray(String[] config,List list){
		if(list == null){
			return new JSONArray();
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(config);
		return JSONArray.fromObject(list, jsonConfig);
	}

	public static JSONObject getJSONObject(String[] config,Object object){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		jsonConfig.setExcludes(config);

		return JSONObject.fromObject(object, jsonConfig);
	}


	public static void mergeJSONObject(JSONObject source,JSONObject target){
		Iterator iterator =  source.keys();
		while (iterator.hasNext()){
			String key = String.valueOf(iterator.next());
			target.put(key, source.get(key));
		}
	}

	public static void mergeJSONObject(JSONObject source,JSONObject target,String[] ignore){
		Iterator iterator =  source.keys();
		while (iterator.hasNext()){
			boolean mark = false;
			String key = String.valueOf(iterator.next());
			for(String ignoreKey:ignore){
				if(ignoreKey.equals(key)){
					mark = true;
					break;
				}
			}
			if(mark){
				continue;
			}
			target.put(key, source.get(key));
		}
	}

	public static String replaceIndex(String resource,String target,int location){
		return resource.substring(0, location) + target + resource.substring(location+1);
	}

	public static String replaceIndexByList(String sql,List<Object> params){
		for(int i = 0;i < params.size();i++){
			sql = ObjectUtils.replaceIndex(sql, "?"+ (i + 1), sql.indexOf("#"));
		}
		return sql;
	}

	/***
	 *
	 * 替换SQL语句中的#，标记为对应的参数编号
	 *
	 * **/
	public static String replaceIndex(String sql){
		int num = 0;

		while(sql.indexOf("#") != -1){
			sql = ObjectUtils.replaceIndex(sql, "?"+num, sql.indexOf("#"));
			num++;
		}

		return sql;
	}

	public static boolean compareCharacter(String a, String b) {
		if (StringUtils.isEmpty(a) || StringUtils.isEmpty(b) || a.length() != b.length()) {
			return false;
		}

		char[] arrayA = a.toLowerCase().toCharArray();
		char[] arrayB = b.toLowerCase().toCharArray();
		Arrays.sort(arrayA);
		Arrays.sort(arrayB);

		return Arrays.equals(arrayA, arrayB);
	}

	private static boolean isSimpleObject(Class<?> claz){
		if(claz.getName().equals(Long.class.getName())){
			return true;
		}else if(claz.getName().equals(Double.class.getName())){
			return true;
		}else if(claz.getName().equals(Float.class.getName())){
			return true;
		}else if(claz.getName().equals(int.class.getName())){
			return true;
		}else if(claz.getName().equals(Integer.class.getName())){
			return true;
		}else if(claz.getName().equals(String.class.getName())){
			return true;
		}
		return false;
	}

	public static List<String> getListBySplitChar(String s,String splitChar){
		List<String> list = new ArrayList<>();
		if(StringUtils.isEmpty(s)){
			return list;
		}

		String[] arr = s.split(splitChar);

		for(String temp: arr){
			list.add(temp);
		}

		return list;
	}

	public static List<String> pareseSelectSQL(String sql){
		List<String> result =  new ArrayList<>();
		String startMarker = "select";
		String endMarker = "from";
		String regex = "(?i)\\b" + Pattern.quote(startMarker) + "(.*?)" + "(?i)\\b" + Pattern.quote(endMarker);
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(sql);
		if (matcher.find()) {
			String[] arr = matcher.group(1).split(",");
			for(String str: arr){
				if(str.toLowerCase().contains("as")){
					result.add(str.substring(str.toLowerCase().lastIndexOf("as") + 2, str.length()).trim());
				}else {
					result.add(str.substring(str.lastIndexOf(".")+1, str.length()).trim());
				}
			}
		} else {
			System.out.println("No match found.");
		}
		return result;
	}
	public static boolean isImage(File file) {
		if (file!=null && file.exists() && file.isFile()) {
			try {
				BufferedImage bi = ImageIO.read(file);
				if (bi != null) {
					return true;
				}
			} catch (IOException e) {
				return false;
			}

		}
		return false;
	}
	public static void main(String[] args) throws Exception{
		/*String sql = "select * from t where 1 = 1 and t.string # # #";
		for(int i = 0;i < 3;i++){
			sql = ObjectUtils.replaceIndex(sql, "?"+i, sql.indexOf("#"));
		}
		System.out.println(sql);*/
		//System.out.println(ObjectUtils.compareCharacter("ABD", "DAB"));
		Object ob1 = "3";
		Object ob2 = "3" ;
		System.out.println(ob1.equals(ob2));
	}
}
